<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button id="connect">连接</button>
  <button id="sendData" disabled="true">发送数据</button>
  <br />
  <h1>后端返回给您的数据为：<p id="result"></p>
  </h1>
  <script>
    let connect = document.querySelector('#connect')
    let sendData = document.querySelector('#sendData')
    let result = document.querySelector('#result')

    let ws = null;

    // 连接
    connect.onclick = function () {
      ws = new WebSocket('ws://127.0.0.1:9999')

      ws.onopen = () => {
        console.log('连接服务端成功！')
        // 连接成功后启用发送数据按钮
        sendData.disabled = false
      }
      ws.onmessage = (msg) => {
        console.log('收到服务端推送的数据了')
        console.log(msg)  // 里面的data就是服务端发送过来的数据
        result.innerHTML = msg.data
      }
      ws.onerror = () => {
        console.log('连接服务端失败！')
        // 连接成功后启用发送数据按钮
        sendData.disabled = true
      }
    }
    // 发送数据
    sendData.onclick = function () {
      ws.send(JSON.stringify({
        "action": "fullScreen",
        "socketType": "fullScreen",
        "chartName": "trend",
        "value": true
      }))
    }
  </script>
</body>

</html>